using System;
using System.Data;
using System.Collections;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using PHSRAG.Utility;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21;
using PHSRAG.Insight.Agreements.Arra;

namespace PHSRAG.Insight.Agreements
{
    public partial class ArraPIQuestionnaireListPage : BasePage
    {
        #region Private Variables

        private ICachePolicy pageCachePolicy;
        private ICachePolicy cachePolicy;
        private DataTable dtPIQuestionnaires = null;

        #endregion Private Variables

        #region Constants

        private const string PIQuestionnairePageName = "ArraPIQuestionnaire.aspx";
        private const string PageCacheKey = "pageCacheKey_6E99E19A-5F6B-4a68-9EF0-6C109063A74D";
        private const string PILandingPageIndexKey = "PILandingPage_DE8265DB-2E86-41c9-AF2A-6F82A3EE73BC";

        #endregion #region Constants

        #region Events

        #region OnInit
        /// <summary>
        /// Page Initialization.
        /// </summary>
        /// <param name="e">Arguments associated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            cachePolicy = (PHSRAG.Insight21.Policy.ICachePolicy)Session[PHSRAG.Insight21.Policy.Names.CachePolicyKey];
            pageCachePolicy = (PHSRAG.Insight21.Policy.ICachePolicy)Session[PHSRAG.Insight21.Policy.Names.PageCachePolicyKey];
        }

        #endregion OnInit

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            annunciator.Message = string.Empty;
            annunciator.Title = string.Empty;
            breadCrumb.Add("PI Questionnaire List", Settings.GetKeyValue("SubNavigation.Agreements.ArraPIQuestionnaireListURL", string.Empty), Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));
            
            try
            {
                if (!Page.IsPostBack)
                {
                    //Load the GridView with the Questionnaires of the Principal Investigator.
                    LoadPIQuestionnaires();
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
            finally
            {
                agreementsSubNavigation.AccessLevel = ((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask;
                //Highlights the MenuItem on the Menu.
                agreementsSubNavigation.SelectedLink = "PI Questionnaire";
            }
        }

        #endregion Page_Load

        #region AgreementsSubNavigation_SubNavigate
        /// <summary>
        /// Purge the cache before navigating to an another page via the sub-navigation links.
        /// </summary>
        /// <param name="sender">The sub-navigation control</param>
        /// <param name="e">Contains event information</param>
        protected void AgreementsSubNavigation_SubNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        #endregion AgreementsSubNavigation_SubNavigate

        #region BreadCrumb_Navigate
        /// <summary>
        /// Purge the cache before navigating to the target page via breadcrumb links.
        /// </summary>
        /// <param name="sender">The BreadCrumb control</param>
        /// <param name="e">Contains event information</param>
        protected void BreadCrumb_Navigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        #endregion BreadCrumb_Navigate

        #region Pager_OnFirstPage
        /// <summary>
        /// Occurs when the FirstPage hyperlink is clicked on the pager.
        /// The page's GridView is reloaded with the data belonging to the first page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void Pager_OnFirstPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = 0;
                LoadPIQuestionnaires();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion Pager_OnFirstPage

        #region Pager_OnNextPage
        /// <summary>
        /// Occurs when the NextPage hyperlink is clicked on the pager.
        /// The page's GridView is reloaded with the data belonging to the next page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void Pager_OnNextPage(object sender, CommandEventArgs e)
        {
            try
            {
                ++CurrentPageIndex;
                LoadPIQuestionnaires();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion Pager_OnNextPage

        #region Pager_OnPreviousPage
        /// <summary>
        /// Occurs when the PreviousPage hyperlink is clicked on the pager.
        /// The page's DataGrid is reloaded with the data belonging to the previous page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void Pager_OnPreviousPage(object sender, CommandEventArgs e)
        {
            try
            {
                --CurrentPageIndex;
                LoadPIQuestionnaires();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion Pager_OnPreviousPage

        #region Pager_OnLastPage
        /// <summary>
        /// Occurs when the LastPage hyperlink is clicked on the pager.
        /// The page's GridView is reloaded with the data belonging to the last page.
        /// </summary>
        /// <param name="sender">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void Pager_OnLastPage(object sender, CommandEventArgs e)
        {
            try
            {
                int lastPageIndex = topPager.PageCount - 1;
                CurrentPageIndex = lastPageIndex;
                LoadPIQuestionnaires();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion Pager_OnLastPage

        #region gvPIQuestionnaires_OnSorting
        /// <summary>
        /// Sort event handler
        /// </summary>
        /// <param name="source">The object raising an event.</param>
        /// <param name="e">Argument associated with the event</param>
        protected void gvPIQuestionnaires_OnSorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (e.SortExpression != string.Empty)
                {
                    CurrentPageIndex = 0;

                    if (e.SortExpression == hdnSortColumn.Value)
                        hdnSortOrder.Value = (PHSRAG.Insight21.InsightUtilities.Constants.SortViewAscending == hdnSortOrder.Value) ? PHSRAG.Insight21.InsightUtilities.Constants.SortViewDescending : PHSRAG.Insight21.InsightUtilities.Constants.SortViewAscending;
                    else
                        hdnSortOrder.Value = PHSRAG.Insight21.InsightUtilities.Constants.SortViewAscending;

                    hdnSortColumn.Value = e.SortExpression;
                    LoadPIQuestionnaires();

                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion gvPIQuestionnaires_OnSorting

        #region gvPIQuestionnaires_OnRowCreated

        protected void gvPIQuestionnaires_OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                Image imgSortOrder = new Image();
                foreach (TableCell tc in e.Row.Cells)
                {
                    if (tc.HasControls())
                    {
                        LinkButton lbLinkButton = (LinkButton)tc.Controls[0];
                        if (hdnSortColumn.Value == lbLinkButton.CommandArgument)
                        {
                            if (hdnSortOrder.Value == PHSRAG.Insight21.InsightUtilities.Constants.SortViewAscending)
                                imgSortOrder.ImageUrl = "../Images/arrowUp.gif";
                            else
                                imgSortOrder.ImageUrl = "../Images/arrowDown.gif";
                            tc.VerticalAlign = VerticalAlign.Bottom;
                            tc.Controls.Add(imgSortOrder);
                        }
                    }
                }
            }
        }

        #endregion gvPIQuestionnaires_OnRowCreated

        #region gvPIQuestionnaires_RowDataBound

        protected void gvPIQuestionnaires_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                DataRowView drv = (DataRowView)e.Row.DataItem;

                Label lblReportingPeriod = e.Row.FindControl("lblReportingPeriod") as Label;
                if (null != lblReportingPeriod)
                {
                    lblReportingPeriod.Text = GetReportingPeriod(drv["QuarterEndDate"].ToString());
                }

                PIQuestionnaireState PIQStatus = (PIQuestionnaireState)drv["PIQuestionnaireStatusId"];

                switch (PIQStatus)
                {
                    case PIQuestionnaireState.Completed:
                        {
                            HtmlAnchor linkQuestionnaire = e.Row.FindControl("linkQuestionnaire") as HtmlAnchor;
                            if (null != linkQuestionnaire)
                            {
                                linkQuestionnaire.HRef = PIQuestionnairePageName + "?Id=" + drv["PIQuestionnaireId"].ToString();
                                string strNarrative = (null != drv["Narrative"] ? drv["Narrative"].ToString() : "");
                                linkQuestionnaire.InnerHtml = (strNarrative.Length > 40 ? strNarrative.ToString().Substring(0, 40) + "..." : strNarrative);
                            }
                        }
                        break;
                    case PIQuestionnaireState.FollowUpNotificationSent:
                    case PIQuestionnaireState.StartNotificationSent:
                    case PIQuestionnaireState.Started:
                    case PIQuestionnaireState.InProcess:
                        ImageButton lnkAction = e.Row.FindControl("ibAction") as ImageButton;
                        if (null != lnkAction)
                        {
                            lnkAction.OnClientClick = "javascript:window.location='" + PIQuestionnairePageName + "?Id=" + drv["PIQuestionnaireId"].ToString() + "';return false;";
                            lnkAction.ImageUrl = (PIQuestionnaireState.Started == PIQStatus ? "../images/b_start.gif" : "../images/b_update.gif");
                            lnkAction.Visible = true;
                        }
                        break;
                }
            }
        }

        #endregion gvPIQuestionnaires_RowDataBound

        #endregion Events

        #region Properties

        #region CurrentPageIndex
        /// <summary>
        /// Get/Set the current page within the datagrid for display. This information persists across page loads.
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.PILandingPageKey) as Hashtable;
                return (h == null || h[PILandingPageIndexKey] == null) ? 0 : (int)h[PILandingPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.PILandingPageKey) as Hashtable ?? new Hashtable();

                h[PILandingPageIndexKey] = value;
                gvPIQuestionnaires.PageIndex = value;
                pageCachePolicy.Cache(Keys.PILandingPageKey, h);
            }
        }

        #endregion CurrentPageIndex

        #endregion Properties
        
        #region Private Methods

        #region DisplayExceptionReport
        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = PHSRAG.Insight21.InsightUtilities.Constants.Annunciator.Title;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        #endregion DisplayExceptionReport

        #region PurgeCache()
        /// <summary>
        /// Purge the cached BO from the cache and remove its key from the cache.
        /// </summary>
        private void PurgeCache()
        {
            System.Diagnostics.Trace.WriteLine("Purging PILandingPage...");
            //ResultsCache.PurgeObject(cachePolicy);
        }

        #endregion PurgeCache()

       

        #region GetReportingPeriod

        private string GetReportingPeriod(string strQuarterEndDate)
        {
            DateTime dt = Convert.ToDateTime(strQuarterEndDate);
            string strReportingPeriod = dt.ToString("MMM") + " 09";
            return strReportingPeriod;
        }

        #endregion GetReportingPeriod

        #region ManagePagination
        /// <summary>
        /// Pagination management
        /// </summary>
        private void ManagePagination()
        {
            int currentPageIndex = CurrentPageIndex;
            gvPIQuestionnaires.PageIndex = currentPageIndex;

            int startIndex = currentPageIndex * gvPIQuestionnaires.PageSize;
            bottomPager.FirstRecord = topPager.FirstRecord = startIndex + 1;

            //int lastRecord = COIUserSummary.Count;
            int lastRecord = dtPIQuestionnaires.Rows.Count;
            bottomPager.LastRecord = topPager.LastRecord =
                Math.Min(startIndex + gvPIQuestionnaires.PageSize, lastRecord);
        }

        #endregion ManagePagination

        #region ManageNavigationLinks
        /// <summary>
        /// Enables or Disables links to other pages within the grid
        /// </summary>
        private void ManageNavigationLinks()
        {
            bottomPager.EnableFirstPage = topPager.EnableFirstPage =
                bottomPager.EnablePreviousPage = topPager.EnablePreviousPage =
                    (gvPIQuestionnaires.PageIndex != 0);

            bottomPager.EnableLastPage = topPager.EnableLastPage =
                bottomPager.EnableNextPage = topPager.EnableNextPage =
                    (gvPIQuestionnaires.PageIndex != (topPager.PageCount - 1));
        }

        #endregion ManageNavigationLinks

        #region LoadPIQuestionnaires
        /// <summary>	
        /// Loads the COIUser Summary details only for those to displayed on the page.
        /// </summary>
        private void LoadPIQuestionnaires()
        {
            int intLoggedInUserId = ((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId;
            int intRecordCount = 0;
            int intStartPageIndex = CurrentPageIndex;
            int intEndingPageIndex = CurrentPageIndex + 1;
            int intPageSize = gvPIQuestionnaires.PageSize;
            string strSortColumn = hdnSortColumn.Value;
            string strSortOrder = hdnSortOrder.Value;
            dtPIQuestionnaires = GetArraPIQuestionnairesByAdmPersonId(intLoggedInUserId, strSortColumn, strSortOrder, intPageSize, intStartPageIndex,out intRecordCount);

            if (null != dtPIQuestionnaires)
            {

                bottomPager.RecordCount = topPager.RecordCount = intRecordCount;
                int currentPageIndex = CurrentPageIndex;
                int pageCount = (topPager.RecordCount / gvPIQuestionnaires.PageSize) +
                    (((topPager.RecordCount % gvPIQuestionnaires.PageSize) == 0) ? 0 : 1);
                bottomPager.PageCount = topPager.PageCount = pageCount;
                bottomPager.CurrentPage = topPager.CurrentPage = currentPageIndex + 1;

                gvPIQuestionnaires.DataSource = dtPIQuestionnaires;
                gvPIQuestionnaires.DataBind();

                if (dtPIQuestionnaires.Rows.Count == 0)
                {
                    gridContainer.Visible = false;
                    annunciator.Message = "There are NO Questionnaires.";
                }
                else
                {
                    gridContainer.Visible = true;
                    annunciator.Message = string.Empty;
                    recordCount.Text = topPager.RecordCount.ToString();
                    ManagePagination();
                    ManageNavigationLinks();
                }
            }
            else
            {
                gridContainer.Visible = false;
                annunciator.Message = string.Empty;
            }

        }
        #endregion LoadPIQuestionnaires

        #region GetArraPIQuestionnairesByAdmPersonId



        /// <summary>
        /// Returns a DataTable with the PIQuestionnaires.
        /// </summary>
        /// <param name="intPIAdmPersonId">Principal Investigator AdmPersonId</param>
        /// <returns>DataTable with PIQuestionnaires</returns>
        private DataTable GetArraPIQuestionnairesByAdmPersonId(int intPIAdmPersonId, string strSortColumn, string strSortOrder, int intPageSize, int intStartPageIndex,out int intRecordCount)
        {
            try
            {
                DataTable dtPIQuestionnaires = DataAccess.GetDataTable(Utility.DataAccess.ConnectionString, "GetArraPIQuestionnairesByAdmPersonId",
                        Utility.DataAccess.BuildSqlParameterArray(
                        "@PIAdmPersonId", SqlDbType.Int, intPIAdmPersonId
                        ));

                intRecordCount = dtPIQuestionnaires.Rows.Count;
                DataRow[] dataRows = dtPIQuestionnaires.Select(string.Empty, string.Format("{0} {1}", strSortColumn, strSortOrder));
                DataTable dtReturnPIQuestionnaires = dtPIQuestionnaires.Clone();

                int intStartIndex = intPageSize * intStartPageIndex;
                for (int i = intStartIndex, end = Math.Min(i + intPageSize, dataRows.Length); i < end; ++i)
                {
                    dtReturnPIQuestionnaires.LoadDataRow(dataRows[i].ItemArray, true);
                }
                return dtReturnPIQuestionnaires;


            }
            catch (Exception e)
            {
                throw new Exception("Failed to load PIQuestionnaires.", e);
            }
        }

        #endregion GetArraPIQuestionnairesByAdmPersonId

        #endregion Private Methods
    }
}

